#!/bin/sh
# The launcher of KumoYami Server.app (Contents/MacOS/KumoYami; packaging/macos/README.md). Opened from the Finder it
# registers the server as a LaunchAgent of the user (~/Library/LaunchAgents/com.kumoyami.server.plist: it starts at
# every login and again if it fails), starts it, and opens http://localhost:<port>/ once it answers. launchd runs this
# same file with --run: the server in the foreground, its output in <data>/logs/kumoyami.log.
#
#   KumoYami              start (or restart) and open the site
#   KumoYami --run        the server itself (launchd)
#   KumoYami --stop       stop it until the next login or the next open
#   KumoYami --uninstall  stop it and remove the LaunchAgent (the data stays)
#
# Data: ~/Library/Application Support/KumoYami, or KUMOYAMI_DATA_DIR; port 4890, or KUMOYAMI_PORT; addresses 0.0.0.0,
# or KUMOYAMI_HOSTNAME (read when the agent is written).
contents=$(cd "$(dirname "$0")/.." && pwd -P) || exit 1
server="$contents/Resources/server"
label=com.kumoyami.server
domain="gui/$(id -u)"
agent="$HOME/Library/LaunchAgents/$label.plist"
data="${KUMOYAMI_DATA_DIR:-$HOME/Library/Application Support/KumoYami}"
port="${KUMOYAMI_PORT:-4890}"
listen="${KUMOYAMI_HOSTNAME:-0.0.0.0}"
log="$data/logs/kumoyami.log"

xml() { printf '%s' "$1" | sed -e 's/&/\&amp;/g' -e 's/</\&lt;/g' -e 's/>/\&gt;/g'; }

case "${1:-}" in
  --run)
    mkdir -p "$data/logs" || exit 1
    # A log that has grown too much starts again; the previous one is kept as kumoyami.log.1
    if [ -f "$log" ] && [ "$(wc -c < "$log")" -gt 5242880 ]; then mv -f "$log" "$log.1"; fi
    printf '\n%s KumoYami Server starting (port %s, data %s)\n' "$(date '+%Y-%m-%d %H:%M:%S')" "$port" "$data" >> "$log"
    export DATA_DIR="$data" PORT="$port" HOSTNAME="$listen" NODE_ENV=production NEXT_TELEMETRY_DISABLED=1
    export FFMPEG_PATH="$server/ffmpeg/ffmpeg" FFPROBE_PATH="$server/ffmpeg/ffprobe"
    export KUMOYAMI_PLATFORM=macos KUMOYAMI_LOG_FILE="$log"
    export PATH="$server/ffmpeg:/usr/bin:/bin:/usr/sbin:/sbin"
    cd "$server/app" || exit 1
    exec "$server/node/bin/node" kumoyami.js >> "$log" 2>&1 < /dev/null
    ;;
  --stop)
    launchctl bootout "$domain/$label" 2> /dev/null
    exit 0
    ;;
  --uninstall)
    launchctl bootout "$domain/$label" 2> /dev/null
    rm -f "$agent"
    exit 0
    ;;
esac

# Opened: the agent with this copy of the app (it may have been moved or updated), started again
mkdir -p "$HOME/Library/LaunchAgents" "$data/logs" || exit 1
cat > "$agent" << EOF
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>Label</key><string>$label</string>
  <key>ProgramArguments</key>
  <array><string>$(xml "$contents/MacOS/KumoYami")</string><string>--run</string></array>
  <key>EnvironmentVariables</key>
  <dict>
    <key>KUMOYAMI_DATA_DIR</key><string>$(xml "$data")</string>
    <key>KUMOYAMI_PORT</key><string>$(xml "$port")</string>
    <key>KUMOYAMI_HOSTNAME</key><string>$(xml "$listen")</string>
  </dict>
  <key>RunAtLoad</key><true/>
  <key>KeepAlive</key><dict><key>SuccessfulExit</key><false/></dict>
  <key>ThrottleInterval</key><integer>10</integer>
  <key>ProcessType</key><string>Interactive</string>
</dict>
</plist>
EOF
launchctl bootout "$domain/$label" 2> /dev/null
launchctl bootstrap "$domain" "$agent" || exit 1

# Open the site once the server answers (up to three minutes: the first start tests the GPU and writes its caches)
i=0
while [ "$i" -lt 180 ]; do
  if curl -s -o /dev/null --max-time 2 "http://127.0.0.1:$port/admin/setup/"; then
    open "http://localhost:$port/"
    exit 0
  fi
  sleep 1
  i=$((i + 1))
done
osascript -e "display notification \"KumoYami Server no ha arrancado: mira $log\" with title \"KumoYami Server\"" 2> /dev/null
exit 1
